import consultasBD
import uuid

from dto import *

import model

import sellManager
import productManager

import dto2ModelFactory
import model2DtoFactory

import ruleSpecFactory

def new_rule(year, month):
    return Rule(None, "", 0, year, month, [], [])

def new_rule_spec(f, t, elements, amount, year, month, type):
    return ruleSpecFactory.create(None, f, t, elements, amount, year, month, type)    
    
def get_rules(year, month):  
    ret = []
    s = model.create_session()
    rulesModel = s.query(model.Rule).filter(model.Rule.year == year).filter(model.Rule.month == month).all()
    for rm in rulesModel:
        ret.append(model2DtoFactory.create_rule(rm))
    
    return ret

def get_all_rules():
    ret = []
    s = model.create_session()
    rulesModel = s.query(model.Rule).all()
    for rm in rulesModel:
        ret.append(model2DtoFactory.create_rule(rm))
        
    return ret       

def store_rule(rule):    
    if not rule.id:
        save_rule(rule)
    else:
        update_rule(rule)       
        
def delete_rule(rule):
    #TODO: EN CASO DE EXCEPCION SE DEBERIA CATHEAR Y RELANZAR CON EL MENSAJE ADECUADO
    s = model.create_session()
    ruleModel = s.query(model.Rule).get(rule.id)
    s.delete(ruleModel)
    s.commit()
    
def save_rule(rule):   
    s = model.create_session()
    ruleModel = dto2ModelFactory.create_rule(rule)
    specsModel = []
    for rs in rule.specs:
        specsModel.append(dto2ModelFactory.create_rule_spec(rs))
        
    ruleModel.specs = specsModel
    
    s.add(ruleModel)
    s.commit()

def update_rule(rule):     
    s = model.create_session()
    ruleModel = s.query(model.Rule).get(rule.id)
    ruleModel.name = rule.name
    ruleModel.points = rule.points
    
    specsModel = []
    for rs in rule.specs:
        if not rs.id:
            specsModel.append(dto2ModelFactory.create_rule_spec(rs))
        else:
            specsModel.append(s.query(model.RuleSpec).get(rs.id))

    for rsm in ruleModel.specs:
        if not rsm in specsModel:
            #TODO: HACER QUE SE BORRE AUTOMATICAMENTE EN CASCADA
            for e in rsm.elements:
                s.delete(e)
                
            s.delete(rsm)
            
    ruleModel.specs = specsModel    
    s.commit()        
    
def get_rule_spec_types():
    return ruleSpecFactory.get_rule_spec_types()
    
def calculate_points(sells, rules):
    points = 0
    for r in rules:
        for s in sells:
            if r.apply(s):
                points += r.points
                
    return points

